import Utils from "../../../Utils";
import Rocket from "../../flyer/DestructibleFlyer/FlyerMissile/Rocket";
import { Killer } from "../../funcObj/interface/HealthPoint";
import { Location } from "../../info/Predefine";
import GameManager from "../../manager/GameManager";
import NodePoolManager from "../../manager/NodePoolManager";
import Player from "../../player/Player";
import LaunchableFalicity from "../LaunchableFalicity";

const { ccclass, property } = cc._decorator;

/**
 * 火箭炮基地
 */
@ccclass
export default class RocketBase extends LaunchableFalicity {

    @property(cc.Node)
    points: cc.Node = null;

    rocketQueue: Array<cc.Node>;

    creating: boolean;

    get count(): number {
        return this.rocketQueue.length
    }

    init(player: Player): void {
        super.init(player);
        this.rocketQueue = [];
        this.creating = false;
        this.creat();
    }

    creat() {
        if (this.creating) return;
        this.CreatingProgress.progress = 0;
        this.CreatingProgress.node.active = true;
        this.creating = true;
        cc.tween(this.CreatingProgress)
            .to(this.makingTime, { progress: 1 })
            .call(() => {
                let rocket = NodePoolManager.instance.obtain(NodePoolManager.instance.rocketBullet);
                rocket.getComponent(Rocket).init(this);
                this.rocketQueue.push(rocket);
                let spacePoint = this.points.children.find(item => !item["record"]);
                let flyerParent = this.player.flyerParentNode;
                rocket.parent = flyerParent;
                rocket.position = flyerParent.convertToNodeSpaceAR(spacePoint.convertToWorldSpaceAR(cc.Vec3.ZERO));
                spacePoint["record"] = rocket;
                this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, 1);
            }).call(() => {
                this.CreatingProgress.node.active = false;
                this.creating = false;
                if (this.rocketQueue.length < this.facilityInfo.每基地可制造上限) {
                    this.creat();
                }
            })
            .start();
    }

    dispatch(target: Location) {
        super.dispatch(target);
        let rocket: cc.Node = this.rocketQueue.shift();
        let spacePoint = this.points.children.find(item => item["record"] === rocket);
        spacePoint["record"] = null;
        this.dispatchQueue.push({ target: target, flyer: rocket })
        this.player.node.emit(Player.EventType.更新飞行物数量, this.facilityType, -1);
        this.creat();
    }

    die(killer: Killer): void {
        super.die(killer);
        this.points.children.forEach(item => item["record"] = null)
        this.rocketQueue.forEach(rocket => NodePoolManager.instance.recycle(rocket));
        this.rocketQueue = null;
    }
}
